package net.arvin.mobilebanksystem.fragment;

import net.arvin.dao.ResponseHandler;
import net.arvin.mobilebanksystem.R;
import net.arvin.mobilebanksystem.activity.CaptureActivity;
import net.arvin.mobilebanksystem.activity.MainActivity;
import net.arvin.model.CodeInfo;
import net.arvin.model.Transfers;
import net.arvin.service.TransfersService;
import net.arvin.utils.DataUtils;
import net.arvin.utils.HttpRequestClient;
import net.arvin.utils.NetConnectionUtil;
import net.arvin.utils.PreferenceUtils;
import net.arvin.utils.TransfersType;
import net.arvin.view.NormalDialog.MyDialogListener;
import net.arvin.view.TransfersDialog;
import net.arvin.view.UrlDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.util.Linkify;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;

public class MainPageFragment extends Fragment implements OnClickListener {

	// private GridView gridView;
	// private List<Map<String, Object>> lists;

	private RelativeLayout scan;
	private RelativeLayout pay;
	private RelativeLayout bill_details;
	private RelativeLayout transfers;
	private RelativeLayout payments;
	private RelativeLayout rechage;

	private TransfersDialog transfersDialog;
	private UrlDialog urlDialog;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_main, null);
		init(view);
		return view;
	}

	private void init(View view) {
		initTitle();
		// initData();
		initView(view);
		initListener();
		setGridViewAdapter();
	}

	private void initTitle() {
		MainActivity.mainActivity.setTitleTv("首页");
		MainActivity.mainActivity.setIsCanOpenMenu(true);
		MainActivity.mainActivity.hidenBackBtn();
	}

	private void setGridViewAdapter() {
		// gridView.setAdapter(new GridViewAdapter(getActivity(), lists));
	}

	private void initListener() {
		// gridView.setOnItemClickListener(this);
		scan.setOnClickListener(this);
		pay.setOnClickListener(this);
		bill_details.setOnClickListener(this);
		transfers.setOnClickListener(this);
		payments.setOnClickListener(this);
		rechage.setOnClickListener(this);
	}

	private void initView(View view) {
		// gridView = (GridView) view.findViewById(R.id.gridview);
		scan = (RelativeLayout) view.findViewById(R.id.scan);
		pay = (RelativeLayout) view.findViewById(R.id.pay);
		bill_details = (RelativeLayout) view.findViewById(R.id.bill_details);
		transfers = (RelativeLayout) view.findViewById(R.id.transfers);
		payments = (RelativeLayout) view.findViewById(R.id.cards);
		rechage = (RelativeLayout) view.findViewById(R.id.recharge);
	}

	// private void initData() {
	// int[] img = { R.drawable.bills_img, R.drawable.transfers_img,
	// R.drawable.payments_img, R.drawable.recharge };
	// String[] title = { "账单详情", "转账汇款", "信用卡还款", "手机充值" };
	//
	// lists = new ArrayList<Map<String, Object>>();
	// for (int i = 0; i < img.length; i++) {
	// Map<String, Object> map = new HashMap<String, Object>();
	// map.put("title", title[i]);
	// map.put("img", img[i]);
	// lists.add(map);
	// }
	// }

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.scan:
			openCaptureActivity();
			break;
		case R.id.pay:
			startFragment("付款码", new PayCodeFragment());
			break;
		case R.id.bill_details:
			startFragment("账单", new BillsFragment());
			break;
		case R.id.transfers:
			startFragment("转账汇款", new TransferFragment());
			break;
		case R.id.cards:
			Toast.makeText(getActivity(), "暂未实现...", Toast.LENGTH_SHORT).show();
			break;
		case R.id.recharge:
			startFragment("手机充值", new RechargeFragment());
			break;
		}
	}

	private void startFragment(String title, Fragment fragment) {
		MainActivity.mainActivity.showBackBtn();
		MainActivity.mainActivity.setTitleTv(title);
		MainActivity.mainActivity.setIsCanOpenMenu(false);
		MainActivity.mainActivity.switchContent(fragment, false);
	}

	private void openCaptureActivity() {
		Intent openCameraIntent = new Intent(getActivity(),
				CaptureActivity.class);
		startActivityForResult(openCameraIntent, 0);
	}

	@SuppressWarnings("static-access")
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// 处理扫描结果（在界面上显示）
		if (resultCode == getActivity().RESULT_OK) {
			Bundle bundle = data.getExtras();
			String url = bundle.getString("result");
			if (url.contains(HttpRequestClient.getSweepUrl())) {
				if (NetConnectionUtil.isConnectWithTip(getActivity(),
						"没有联网=_=!")) {
					TransfersService.trySweepCode(url, getResponseHandler(),
							getActivity());
				}
			} else {
				showNormalDialog(url);
			}
		}
	}

	private void showNormalDialog(String url) {
		urlDialog = new UrlDialog(getActivity(), R.style.MyDialog,
				new MyDialogListener() {

					@Override
					public void onClick(View view) {
						switch (view.getId()) {
						case R.id.dialog_btn_ok:
							urlDialog.dismiss();
							break;
						}
					}
				});
		urlDialog.messages = (TextView) urlDialog.getWindow().findViewById(
				R.id.dialog_messages);
		urlDialog.messages.setTextSize(12f);
		urlDialog.messages.setAutoLinkMask(Linkify.ALL);
		urlDialog.setMessages(url);
		urlDialog.show();
	}

	private void showSweepResultDialog(final CodeInfo codeInfo) {
		transfersDialog = new TransfersDialog(getActivity(), R.style.MyDialog,
				new MyDialogListener() {

					@Override
					public void onClick(View view) {
						switch (view.getId()) {
						case R.id.dialog_btn_cancel:
							transfersDialog.dismiss();
							break;
						case R.id.dialog_btn_ensure:
							commitTransfers(codeInfo);
							transfersDialog.dismiss();
							break;
						}
					}
				});
		transfersDialog.transfers = (TextView) transfersDialog.getWindow()
				.findViewById(R.id.transfer);
		transfersDialog.inputContent = (EditText) transfersDialog.getWindow()
				.findViewById(R.id.dialog_input);
		transfersDialog.setTransfersText(codeInfo.getPhonenumber(),
				codeInfo.getMoney());
		transfersDialog.show();
	}

	private void commitTransfers(final CodeInfo codeInfo) {
		String password = transfersDialog.getInputContent();
		if (password == null || password.equals("")) {
			Toast.makeText(getActivity(), "密码不能为空~", Toast.LENGTH_SHORT).show();
			return;
		}
		Transfers transfers = new Transfers();

		transfers.setToPhone(codeInfo.getPhonenumber());
		transfers.setMoney(Float.valueOf(codeInfo.getMoney()));

		transfers.setType(TransfersType.U2U);
		transfers.setFromPhone(PreferenceUtils
				.getPreferPhonenumber(getActivity()));
		transfers.setTime(DataUtils.getCurrentTime());
		String transfersJson = JSON.toJSONString(transfers);
		if (NetConnectionUtil.isConnectWithTip(getActivity(), "没有联网=_=!")) {
			TransfersService.tryTransferMoney(transfersJson, codeInfo.getId(),
					password, getTransfersResponseHandler(), getActivity());
		}
	}

	private ResponseHandler getResponseHandler() {
		ResponseHandler mResponseHandler = new ResponseHandler() {
			@Override
			public void onRequsetSucceeded(final Object data) {
				CodeInfo codeInfo = JSON.parseObject(data.toString(),
						CodeInfo.class);
				showSweepResultDialog(codeInfo);
			}

			@Override
			public void onRequestFailed(final Object data) {
				Toast.makeText(getActivity(), "获取失败=_=!", Toast.LENGTH_SHORT)
						.show();
			}
		};
		return mResponseHandler;
	}

	private ResponseHandler getTransfersResponseHandler() {
		ResponseHandler mResponseHandler = new ResponseHandler() {
			@Override
			public void onRequsetSucceeded(final Object data) {
			}

			@Override
			public void onRequestFailed(final Object data) {
			}
		};
		return mResponseHandler;
	}
}
